package cn.ultrarisk.scadmin.manager.web.controller.system;

import cn.ultrarisk.scadmin.manager.util.IOUtil;
import cn.ultrarisk.scadmin.manager.web.controller.BaseController;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * SqlRunController
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/6/26
 * @since V1.0
 */
@Controller
@RequestMapping(value = "/system/sql")
public class SqlController extends BaseController {
    @Autowired
    private DruidDataSource dataSource;

    @ResponseBody
    @RequestMapping(value = "/run", method = RequestMethod.POST)
    public ResponseEntity<Map<String, Object>> run(HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();

        String sql = IOUtil.in2Str(request.getInputStream(), "utf-8").replaceAll("(;)+", ";\n").trim();
        if (!sql.endsWith(";")) {
            sql += ";";
        }

        Reader reader = new StringReader(sql);
        StringWriter logSW = new StringWriter();
        PrintWriter logPW = new PrintWriter(logSW);
        try {

            ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
            runner.setAutoCommit(true);
            runner.setStopOnError(true);
            runner.setLogWriter(logPW);
            runner.runScript(reader);

            result.put("flag", true);
            result.put("msg", logSW.toString());
        } catch (Exception e) {
            result.put("flag", false);
            result.put("msg", e.getMessage());
        } finally {
            reader.close();
            logSW.close();
            logPW.close();
        }

        return getOkResponseEntity(result);
    }
}
